//
//  BDBeidouPayViewController.m
//  BeidouMall
//
//  Created by qie on 16/5/30.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDBeidouPayViewController.h"
#import "BDNavigationController.h"
#import "BDAddrMyViewController.h"
#import "BDPaySuccessViewController.h"
#import "BDOrderHomeViewController.h"

@interface BDBeidouPayViewController () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIActionSheetDelegate>
{
    NSDictionary *_addrDic;
    NSArray *_addrList;
    NSString *_addressId;
    NSString *_expressType;
    NSString *_bdAddress;
    NSString *_payType;
    NSMutableArray *_priceList;
    NSMutableArray *_orderList;
    UITableView *_innerTableView;
    NSString *_tradeID;
    
    NSArray *_youhuiList;
    NSInteger _selectedSection;
    
    BOOL notCalculateSingleOrder;
    
    CGFloat _good_total_price;// 商品金额(打折前不含运费)
    CGFloat _expressPrice;// 运费
    CGFloat _privilege;// 优惠券
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceTitleLabel;

@property (weak, nonatomic) IBOutlet UITableView *youhuiTableView;

@property (weak, nonatomic) IBOutlet UIView *popView;

@end

@implementation BDBeidouPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 标题国际化
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont fontWithName:@"BZDHT" size:12.0]}];
    } else {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]}];
    }
    self.title = NSLocalizedString(@"Settlement center", nil);
    if (self.isConveniency) {// 背兜超人
        _expressType = @"BD";
        _bdAddress = @"OLD_CITY";
    } else {
        _expressType = @"REMOTE";
    }
    _payType = @"ALIPAY";
    
    _priceList = [NSMutableArray array];
    _orderList = [NSMutableArray array];
    [self reloadData:self];
    [self orderSetting];// 构造支付时订单数据结构
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMyKeyboard)];
    [self.view addGestureRecognizer:tap];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES
//    tap.cancelsTouchesInView = NO;
    
    //获取通知中心单例对象
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(weixinPayResult:) name:@"weixinPay" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _selectedSection = 0;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!notCalculateSingleOrder) {
        [self calculateSingleOrder];
//        notCalculateSingleOrder = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender {
    NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@",[BDNetworking shareInstance].baseUrl,Addr_Query,[BDAccountManagerModel shareInstance].userId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"获取地址失败:%@",error);
            [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Get address failed", nil)];
        } else {
            NSLog(@"result = %@",results);
            _addrList = (NSArray *)results;
            if (_addrDic == nil && _addrList.count > 0) {
                for (NSDictionary *dic in _addrList) {
                    if (![dic[@"region"] isEqual:[NSNull null]] &&
                        ![dic[@"detailAddress"] isEqual:[NSNull null]]) {
                        if (![dic[@"defaultAddress"] isEqual:[NSNull null]]) {
                            if ([dic[@"defaultAddress"] integerValue] == 1) {
                                _addrDic = dic;
                            }
                        }
                    }
                }
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            });
        }
    }];
}

- (void)calculateSingleOrder {// 获得单个订单的运费，总价
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
    _priceList = [NSMutableArray array];
    int count = 0;
    __block CGFloat getTotalPrice = 0.0;
    
    _good_total_price = 0;// 商品金额(打折前不含运费)
    _expressPrice = 0;// 运费
    _privilege = 0;// 优惠券
    
    for (NSArray *goodList in self.payList) {// 多个订单
        NSString *storeId = goodList[0][@"storeId"];
        NSString *couponId = goodList[0][@"couponId"];
        
        count++;
        NSMutableArray *dataList = [NSMutableArray array];
        for (NSDictionary *dic in goodList) {
            NSDictionary *dataDic = @{@"commodityId" : dic[@"commodityId"],
                                      @"num" : dic[@"num"]};
            [dataList addObject:dataDic];
        }
        NSDictionary *parameters;
        if ([couponId isEqual:[NSNull null]]) {
            parameters = @{@"storeId":storeId,
                           @"userId":[BDAccountManagerModel shareInstance].userId,
                           @"commoditys":dataList};
        } else {
            parameters = @{@"storeId":storeId,
                           @"userId":[BDAccountManagerModel shareInstance].userId,
                           @"couponId":couponId,
                           @"commoditys":dataList};
        }
        
        NSString *url;
        if ([_expressType isEqualToString:@"BD"]) {
            url = [NSString stringWithFormat:@"%@%@?expressType=%@&bdAddress=%@",[BDNetworking shareInstance].baseUrl,CalculateOrder,_expressType,_bdAddress];
        } else {
            url = [NSString stringWithFormat:@"%@%@?expressType=%@",[BDNetworking shareInstance].baseUrl,CalculateOrder,_expressType];
        }
        
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:parameters completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"计算单个订单失败:%@",error);
                hud.labelText = @"计算单个订单失败";
                [hud hideAfterDelay:0.5];
            } else {
                [hud hideAfterDelay:0.5];
                NSLog(@"result = %@",results);
                NSDictionary *dic = (NSDictionary *)results;
                
                // 获取优惠券(可能有一个或没有)
                if (![dic[@"coupon"] isEqual:[NSNull null]]) {
                    NSString *coupon_ID = dic[@"coupon"][@"id"];
                    NSString *coupon_Name = dic[@"coupon"][@"name"];
                    NSMutableDictionary *goodDic = (NSMutableDictionary *)goodList[0];
                    [goodDic setValue:coupon_ID forKeyPath:@"couponId"];
                    [goodDic setValue:coupon_Name forKeyPath:@"couponName"];
                }
                
                CGFloat totalPrice = [dic[@"totalPrice"] floatValue];
                getTotalPrice += totalPrice;
                
                CGFloat goodTotalPrice = [dic[@"commodityPrice"] floatValue];
                _good_total_price += goodTotalPrice;
                
                CGFloat expressTotalPrice = [dic[@"expressPrice"] floatValue];
                _expressPrice += expressTotalPrice;
                
                CGFloat privilegeTotalPrice = [dic[@"privilege"] floatValue];
                _privilege += privilegeTotalPrice;
                
                
                
                NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                NSString *commodityId = goodList[0][@"commodityId"];
                [resultDic setValue:commodityId forKey:@"commodityId"];
                [_priceList addObject:resultDic];
                if (count == self.payList.count) {
                    // 最后一次
                    
                    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.1);
                    dispatch_after(time, dispatch_get_main_queue(), ^{
                        // 底部刷新
                        self.totalPriceTitleLabel.text = NSLocalizedString(@"Amount:", nil);
                        self.totalPriceLabel.text = [NSString stringWithFormat:@"¥%.2f",getTotalPrice];
                    });
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 仅刷新tableView最后一行
                        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:7 inSection:0];
                        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                        
                        
                        [_innerTableView reloadData];
                        if ([_expressType isEqualToString:@"BD"]) {
                            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
                            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                            UIButton *btn = (UIButton *)[cell viewWithTag:101];
                            NSString *title;
                            if ([_bdAddress isEqualToString:@"OLD_CITY"]) {
                                
                                title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"old city", nil)];
                            } else if ([_bdAddress isEqualToString:@"NEW_CITY"]) {
                                
                                title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"new city", nil)];
                            } else if ([_bdAddress isEqualToString:@"SOUTH"]) {
                                
                                title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"southern suburbs", nil)];
                            }
                            [btn setTitle:title forState:UIControlStateNormal];
                            [btn setTitle:title forState:UIControlStateSelected];
                        }
                    });
                }
            }
        }];
    }
}

- (void)orderSetting {// 构造支付接口需要的数据结构
    for (NSArray *goodList in self.payList) {// 多个订单
        NSMutableArray *dataList = [NSMutableArray array];
        for (NSDictionary *dic in goodList) {// 多个商品
            NSDictionary *dataDic = @{@"commodityId" : dic[@"commodityId"],
                                      @"num" : dic[@"num"]};
            [dataList addObject:dataDic];
        }
        
        NSDictionary *dic;
        dic = @{@"remark" : @"",
                @"commoditys" : dataList};
        NSMutableDictionary *goodDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [_orderList addObject:goodDic];
    }
}

- (void)addCouponToOrder {// 最后结算之前加入订单数据
    NSMutableArray *tempOrderList = [NSMutableArray arrayWithArray:_orderList];
    [_orderList removeAllObjects];
    
    NSInteger section = 0;
    for (NSArray *goodList in self.payList) {// 多个订单
        NSMutableArray *dataList = [NSMutableArray array];
        for (NSDictionary *dic in goodList) {// 多个商品
            NSDictionary *dataDic = @{@"commodityId" : dic[@"commodityId"],
                                      @"num" : dic[@"num"]};
            [dataList addObject:dataDic];
        }
        
        NSString *couponId = goodList[0][@"couponId"];
        NSString *remark = tempOrderList[section][@"remark"];
        
        NSDictionary *dic;
        if (![couponId isEqual:[NSNull null]]) {
            dic = @{@"remark" : remark,
                    @"couponId" : couponId,
                    @"commoditys" : dataList};
        } else {
            dic = @{@"remark" : remark,
                    @"commoditys" : dataList};
        }
        
        NSMutableDictionary *goodDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [_orderList addObject:goodDic];
        
        section++;
    }
    
//    NSInteger section = 0;
//    for (NSArray *goodList in self.payList) {// 多个订单
//        NSString *couponId = goodList[0][@"couponId"];// 把每一个订单的头一个取出来couponId放在里面
//        NSString *commodityId = goodList[0][@"commodityId"];// 把每一个订单的头一个商品id取出来
//        if (![couponId isEqual:[NSNull null]]) {// section对应的是订单序列 0对应的是头一个商品
//            NSString *commId = _orderList[section][@"commoditys"][0][@"commodityId"];
//            if ([commodityId isEqualToString:commId]) {
//                NSMutableDictionary *dic = (NSMutableDictionary *)_orderList[section];
//                [dic setValue:couponId forKey:@"couponId"];// 放在单个订单最外部
//            }
//        }
//        section++;
//    }
}

-(void)dismissMyKeyboard {// 收起键盘的手势
    [self.view endEditing:YES];
}

- (void)tableViewSelectedMethod {// 收起键盘的手势会使tableview点击事件失灵,所以使用button点击事件
    dispatch_async(dispatch_get_main_queue(), ^{
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"AddrStoryboardID"];
        BDAddrMyViewController *addrVc = (BDAddrMyViewController *)nav_addrVc.topViewController;
        addrVc.flag = @"clickable";
        [self presentViewController:nav_addrVc animated:YES completion:nil];
        addrVc.block = ^(NSString *str){
            NSLog(@"addr is str = %@",str);
            if ([str isEqualToString:@"noAddr"]) {
                _addrDic = nil;
                NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            } else {
                _addrDic = [NSString dictionaryWithJsonString:str];
                NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            }
        };
    });
}

- (void)commitOrder {// 提交订单
    [self.view endEditing:YES];
    
    if (![WXApi isWXAppInstalled] && [_payType isEqualToString:@"WECHAT"]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"WeChat not installed cannot pay", nil)];
    } else if (_addressId.length == 0){
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"No address selected", nil)];
    } else {
        [self addCouponToOrder];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"paying...", nil)];
        NSDictionary *parameters;
        if (_bdAddress == nil) {
            parameters = @{@"userId":[BDAccountManagerModel shareInstance].userId,
                           @"addressId":_addressId,
                           @"expressType":_expressType,
                           @"payType":_payType,
                           @"deleteCart":@(self.isFromShopCart),
                           @"orders":_orderList};
        } else {
            parameters = @{@"userId":[BDAccountManagerModel shareInstance].userId,
                           @"addressId":_addressId,
                           @"expressType":_expressType,
                           @"payType":_payType,
                           @"deleteCart":@(self.isFromShopCart),
                           @"bdAddress":_bdAddress,
                           @"orders":_orderList};
        }
        
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,GoodCommit];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"POST" parameters:parameters completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"付款失败:%@",error);
                hud.labelText = NSLocalizedString(@"pay fail", nil);
                [hud hideAfterDelay:0.5];
            } else {
                [hud hideAfterDelay:0.1];
                NSLog(@"result = %@",results);
                NSString *data = (NSString *)results;
                if ([_payType isEqualToString:@"ALIPAY"]) {
                    [self aliPayWithOrder:data Callback:^(NSDictionary *results) {// 支付宝的回调
                        NSLog(@"支付结果reslut = %@",results);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSInteger code = [[results valueForKey:@"resultStatus"] integerValue];
                            NSString *type;
                            if (code == 9000) {
                                NSString *tradeID = [self dataProcess:data];
                                if (![tradeID isEqual:[NSNull null]]) {// 成功后需要调用付款成功通知
                                    NSString *url = [NSString stringWithFormat:@"%@%@?tradeId=%@",[BDNetworking shareInstance].baseUrl,PaySuccess,tradeID];
                                    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
                                        if (error != nil) {
                                            NSLog(@"付款成功通知失败:%@",error);
                                        } else {
                                            NSLog(@"result = %@",results);
                                        }
                                    }];
                                }
                                type = @"success";
                            } else {
                                type = @"fail";
                            }
                            [self payFinishMethod:type];
                        });
                        
                    }];
                } else if ([_payType isEqualToString:@"WECHAT"]) {
                    NSDictionary *dic = [self dataProcess2:data];
                    //调起微信支付
                    PayReq* req = [[PayReq alloc] init];
                    req.openID = [dic objectForKey:@"appid"];
                    req.partnerId = [dic objectForKey:@"partnerid"];
                    req.prepayId = [dic objectForKey:@"prepayid"];
                    req.nonceStr = [dic objectForKey:@"noncestr"];
                    NSNumber *time = [dic objectForKey:@"timestamp"];
                    req.timeStamp = [time unsignedIntValue];
                    req.package = [dic objectForKey:@"package"];
                    req.sign = [dic objectForKey:@"sign"];
                    [WXApi sendReq:req];
                }
            }
        }];
    }
}

- (void)aliPayWithOrder:(NSString *) order Callback:(void(^)(NSDictionary *results))callBack {// 支付宝回调
    //应用注册scheme 便于支付结束后重新打开客户端
    NSString *appScheme = @"BeidouMall";
    NSLog(@"签名字符串:%@",order);
    [[AlipaySDK defaultService] payOrder:order fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        callBack(resultDic);
    }];
}

- (NSString *)dataProcess:(NSString *)string {// 从字符串中取数据
    NSArray *array = [string componentsSeparatedByString:@"&"];
    for (NSString *str in array) {// out_trade_no
        NSArray *array = [str componentsSeparatedByString:@"="];
        NSString *key = array[0];
        if ([key isEqualToString:@"out_trade_no"]) {
            return array[1];
        }
    }
    return nil;
}

- (NSDictionary *)dataProcess2:(NSString *)string {// 从字符串中取数据
    NSArray *array = [string componentsSeparatedByString:@"&"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSString *str in array) {// out_trade_no
        NSArray *array = [str componentsSeparatedByString:@"="];
        NSString *key = array[0];
        NSString *value;
        if ([key isEqualToString:@"package"]) {
            value = [NSString stringWithFormat:@"%@=%@",array[1],array[2]];
        } else {
            if ([key isEqualToString:@"out_trade_no"]) {
                _tradeID = array[1];
            }
            value = array[1];
        }
        [dic setValue:value forKey:key];
    }
    return dic;
}

- (void)weixinPayResult:(id) sender {// 微信的回调
    NSLog(@"%@",sender);
    NSNotification *notificaion = (NSNotification *)sender;
    NSDictionary *dic = notificaion.userInfo;
    
    NSInteger code = [[dic valueForKey:@"errCode"] integerValue];
    NSString *type;
    if (code == 0) {
        NSString *url = [NSString stringWithFormat:@"%@%@?tradeId=%@",[BDNetworking shareInstance].baseUrl,PaySuccess,_tradeID];
        [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            if (error != nil) {
                NSLog(@"付款成功通知失败:%@",error);
            } else {
                NSLog(@"result = %@",results);
            }
        }];
        type = @"success";
    } else {
        type = @"fail";
    }
    [self payFinishMethod:type];
}

- (void)payFinishMethod:(NSString *)result {
    [BDAccountManagerModel shareInstance].payResult = result;
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 展示优惠券列表按钮
- (void)youhuiButtonPressed:(UIButton *) sender {
    self.popView.hidden = NO;
    _youhuiList = @[];
    
    NSInteger section = sender.superview.tag - 800;
    NSArray *arr = _payList[section];
    _selectedSection = section;
    NSString *storeId = arr[0][@"storeId"];
    
    NSMutableArray *dataList = [NSMutableArray array];
    for (NSDictionary *dic in arr) {
        NSString *commodityID = dic[@"commodityId"];
        [dataList addObject:commodityID];
    }
    NSString *commoditys = [dataList componentsJoinedByString:@","];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=UNUSED&overdue=%@&storeId=%@&commodityIds=%@",
                     [BDNetworking shareInstance].baseUrl,
                     Youhui_Query,
                     (long)1,
                     100,
                     [BDAccountManagerModel shareInstance].userId,
                     @"no",
                     storeId,
                     commoditys];
    
    MBProgressHUD *hud;
    
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"优惠券列表获取失败:%@",error);
            if (hud) {
                hud.labelText = @"优惠券列表获取失败";
                [hud hideAfterDelay:0.5];
            } else {
                [MBProgressHUD showToast:self.view withText:@"优惠券列表获取失败"];
            }
        } else {
            if (hud) {
                [hud hideAfterDelay:0.5];
            }
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if (resultList.count > 0) {
                    _youhuiList = resultList;
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_youhuiTableView reloadData];
                });
            }
        }
    }];
}

#pragma mark tableView dataSrouce

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        return 1;
    } else if (tableView == self.youhuiTableView) {
        return 1;
    } else {
        return _payList.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return 8;
    } else if (tableView == self.youhuiTableView) {
        if (_youhuiList.count >= 5) {
            _youhuiTableView.scrollEnabled = YES;
        } else {
            _youhuiTableView.scrollEnabled = NO;
        }
        return _youhuiList.count > 0 ? _youhuiList.count : 1;
    } else {
        NSArray *arr = _payList[section];
        return arr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        if (indexPath.row == 0) {
            static NSString *cellStr = @"addrCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            UIButton *btn = (UIButton *)[cell viewWithTag:301];
            [btn addTarget:self action:@selector(tableViewSelectedMethod) forControlEvents:UIControlEventTouchUpInside];
            
            if (_addrDic) {
                [[cell viewWithTag:101] setHidden:NO];
                [[cell viewWithTag:102] setHidden:NO];
                [[cell viewWithTag:103] setHidden:NO];
                [[cell viewWithTag:104] setHidden:NO];
                [[cell viewWithTag:105] setHidden:YES];
                
                NSString *addrID = _addrDic[@"id"];
                if (![addrID isEqual:[NSNull null]]) {
                    _addressId = addrID;
                }
                
                UILabel *nameLabel = (UILabel *)[cell viewWithTag:101];
                if (![_addrDic[@"receiver"] isEqual:[NSNull null]]) {
                    nameLabel.text = _addrDic[@"receiver"];
                } else {
                    nameLabel.text = @"未知";
                }
                UILabel *phoneLabel = (UILabel *)[cell viewWithTag:102];
                if (![_addrDic[@"telephone"] isEqual:[NSNull null]]) {
                    NSString *telephone = _addrDic[@"telephone"];
                    if ([telephone isVaildEmail]) {
                        phoneLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"Email", nil),_addrDic[@"telephone"]];
                        
                    } else {
                        phoneLabel.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"Phone", nil),_addrDic[@"telephone"]];
                    }
                } else {
                    phoneLabel.text = [NSString stringWithFormat:@"电话：未知"];
                }
                UILabel *aadrLabel = (UILabel *)[cell viewWithTag:103];
                if (![_addrDic[@"region"] isEqual:[NSNull null]] &&
                    ![_addrDic[@"detailAddress"] isEqual:[NSNull null]]) {
                    if (![_addrDic[@"defaultAddress"] isEqual:[NSNull null]]) {
                        if ([_addrDic[@"defaultAddress"] integerValue] == 1) {
                            NSString *str = [NSString stringWithFormat:@"%@%@%@",NSLocalizedString(@"[Default address]", nil),_addrDic[@"region"],_addrDic[@"detailAddress"]];
                            NSInteger index = 0;
                            if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
                                index = 17;
                            } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
                                index = 6;
                            }
                            NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:str];
                            [attriStr addAttribute:NSForegroundColorAttributeName value:RGBColor(255, 66, 0) range:NSMakeRange(0, index)];
                            [attriStr addAttribute:NSForegroundColorAttributeName value:RGBColor(206, 206, 206) range:NSMakeRange(index, attriStr.length - index)];
                            [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attriStr.length)];
                            aadrLabel.attributedText = attriStr;
                        } else {
                            aadrLabel.text = [NSString stringWithFormat:@"%@%@",_addrDic[@"region"],_addrDic[@"detailAddress"]];
                        }
                    }
                } else {
                    aadrLabel.text = @"地址未知";
                }
            } else {
                [[cell viewWithTag:101] setHidden:YES];
                [[cell viewWithTag:102] setHidden:YES];
                [[cell viewWithTag:103] setHidden:YES];
                [[cell viewWithTag:104] setHidden:YES];
                [[cell viewWithTag:105] setHidden:NO];
            }
            
            return cell;
        } else if (indexPath.row == 1) {
            static NSString *cellStr = @"sendMethodCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            UILabel *label = (UILabel *)[cell viewWithTag:201];
            label.hidden = [_expressType isEqualToString:@"BD"] ? NO : YES;
            
            return cell;
        } else if (indexPath.row == 2) {
            NSString *cellStr = self.isConveniency ? @"sendCell" : @"sendCell2";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            if ([cellStr isEqualToString:@"sendCell"]) {
                UIButton *btn = (UIButton *)[cell viewWithTag:101];
                NSString *title;
                if ([_bdAddress isEqualToString:@"OLD_CITY"]) {
                    
                    title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"old city", nil)];
                } else if ([_bdAddress isEqualToString:@"NEW_CITY"]) {
                    
                    title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"new city", nil)];
                } else if ([_bdAddress isEqualToString:@"SOUTH"]) {
                    
                    title = [NSString stringWithFormat:@" %@(%@)",NSLocalizedString(@"Beidou Express", nil),NSLocalizedString(@"southern suburbs", nil)];
                }
                [btn setTitle:title forState:UIControlStateNormal];
                [btn setTitle:title forState:UIControlStateSelected];
                
                UIButton *btn2 = (UIButton *)[cell viewWithTag:102];
                
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    btn.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                    btn2.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                }
            }
            
            return cell;
        } else if (indexPath.row == 3) {
            static NSString *cellStr = @"goodTitleCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            return cell;
        } else if (indexPath.row == 4) {
            static NSString *cellStr = @"innerTableViewCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            _innerTableView = (UITableView *)[cell viewWithTag:101];
            return cell;
        } else if (indexPath.row == 5) {
            static NSString *cellStr = @"payMethodCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            return cell;
        } else if (indexPath.row == 6) {
            static NSString *cellStr = @"payCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            UIButton *aliPayButton = (UIButton *)[cell viewWithTag:101];
            CGFloat labelWidth = 75;
            CGFloat imageWidth = 16;
            
            if (kScreen_Width <= 320.0) {
                aliPayButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + 5, 0, -labelWidth - 5);
            } else {
                aliPayButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + 15, 0, -labelWidth - 5);
            }
            
            aliPayButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
            
            UIButton *wechatButton = (UIButton *)[cell viewWithTag:102];
            wechatButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
            wechatButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
            
            if (kScreen_Width <= 320.0) {
                aliPayButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
                wechatButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    aliPayButton.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:11.0];
                    wechatButton.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:11.0];
                }
            }
            
            return cell;
        } else {
            static NSString *cellStr = @"totalCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            UILabel *goodLabel = (UILabel *)[cell viewWithTag:101];
            goodLabel.text = [NSString stringWithFormat:@"¥%.2f",_good_total_price];
            
            UILabel *expressLabel = (UILabel *)[cell viewWithTag:102];
            expressLabel.text = [NSString stringWithFormat:@"¥%.2f",_expressPrice];
            
            UILabel *privilegeLabel = (UILabel *)[cell viewWithTag:103];
            privilegeLabel.text = [NSString stringWithFormat:@"¥%.2f",_privilege];
            
            return cell;
        }
    } else if (tableView == self.youhuiTableView) {
        if (_youhuiList.count > 0) {
            static NSString *cellStr = @"customCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            UILabel *nameLabel = (UILabel *)[cell viewWithTag:101];
            NSString *name = _youhuiList[indexPath.row][@"name"];
            if (![name isEqual:[NSNull null]]) {
                nameLabel.text = name;
            }
            UIImageView *imageView = [(UIImageView *)cell viewWithTag:102];
            imageView.image = [UIImage imageNamed:@"youhuiquan_unselected"];
            // 展示优惠券id
            NSString *couponId = _youhuiList[indexPath.row][@"id"];
            // 已选择的优惠券id
            NSString *couponId_selected = _payList[_selectedSection][0][@"couponId"];
            if (![couponId isEqual:[NSNull null]] &&
                ![couponId_selected isEqual:[NSNull null]]) {
                if ([couponId isEqualToString:couponId_selected]) {
                    imageView.image = [UIImage imageNamed:@"youhuiquan_selected"];
                }
            }
            
            return cell;
        } else {
            static NSString *cellStr = @"noCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
            
            return cell;
        }
        
    } else {
        static NSString *cellStr = @"goodCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        // 商品图片
        NSString *storeImageUrl = self.payList[indexPath.section][indexPath.row][@"icon"];
        UIImageView *storeImageView = (UIImageView *)[cell viewWithTag:101];
        if (![storeImageUrl isEqual:[NSNull null]]) {
            NSInteger width = storeImageView.width * 2;
            NSInteger height = storeImageView.height * 2;
            storeImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",storeImageUrl,(long)width,(long)height];
            [storeImageView sd_setImageWithURL:[NSURL URLWithString:storeImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
        }
        
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *goodName = self.payList[indexPath.section][indexPath.row][@"name"];
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        
        UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:103];
        NSNumber *price = self.payList[indexPath.section][indexPath.row][@"price"];
        goodPriceLabel.text = [NSString stringWithFormat:@"¥ %.2f",[price floatValue]];
        
        UILabel *numLabel = (UILabel *)[cell viewWithTag:104];
        NSString *num = self.payList[indexPath.section][indexPath.row][@"num"];
        if (![num isEqual:[NSNull null]]) {
            numLabel.text = [NSString stringWithFormat:@"%@x%ld",NSLocalizedString(@"quantity", nil),(long)[num integerValue]];
            if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                numLabel.text = [NSString stringWithFormat:@"%@x%ld",@"数量：",(long)[num integerValue]];
            }
        }
        
        return cell;
    }
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        if (indexPath.row == 0) {
            CGFloat textHeight = 37.0;
            NSDictionary *addrDic = (NSDictionary *)_addrDic;
            NSString *addr;
            if (![addrDic[@"region"] isEqual:[NSNull null]] &&
                ![addrDic[@"detailAddress"] isEqual:[NSNull null]]) {
                if (![addrDic[@"defaultAddress"] isEqual:[NSNull null]]) {
                    if ([addrDic[@"defaultAddress"] integerValue] == 1) {
                        addr = [NSString stringWithFormat:@"%@%@%@",NSLocalizedString(@"[Default address]", nil),_addrDic[@"region"],_addrDic[@"detailAddress"]];
                    } else {
                        addr = [NSString stringWithFormat:@"%@%@",_addrDic[@"region"],_addrDic[@"detailAddress"]];
                    }
                }
                textHeight = [addr boundingHeightWithSize:CGSizeMake(kScreen_Width - 36.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:14.0] lineSpace:8.0] + 10;
                textHeight = textHeight < 27.0 ? 27.0 : textHeight;
            }
            return textHeight + 48.0;// 75.0 - 27.0 = 48.0
        } else if (indexPath.row == 4) {
            int count = 0;
            for (NSArray *list in self.payList) {
                count += list.count;
            }
            return count * 78.0 + self.payList.count * (25.0 + 121.0);
            
        } else if (indexPath.row == 3) {
            return 44;
        } else if (indexPath.row == 7) {
            return 105.0;
        }
        return 50.0;
    } else if (tableView == self.youhuiTableView) {
        return _youhuiList.count > 0 ? 44.0 : 248.0;
    } else {
        return 78.0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        
    } else if (tableView == self.youhuiTableView) {
       
    } else {
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView != self.tableView && tableView != self.youhuiTableView) {
        return 25.0;
    }
    return 0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView != self.tableView && tableView != self.youhuiTableView) {
        UIView *header = [[[NSBundle mainBundle] loadNibNamed:@"BDPayInnerHeaderView" owner:nil options:nil] lastObject];
        UIView *view = [header viewWithTag:101];
        
        UILabel *nameLabel = (UILabel *)[view viewWithTag:201];
        NSString *name = self.payList[section][0][@"storeName"];
        nameLabel.text = name;
        
        return header;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView != self.tableView && tableView != self.youhuiTableView) {
        return 121.0;
    }
    return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (tableView != self.tableView && tableView != self.youhuiTableView) {
        UIView *footer = [[[NSBundle mainBundle] loadNibNamed:@"BDPayInnerFooterView" owner:nil options:nil] lastObject];
        footer.tag = 800 + section;
        
        UIButton *youhuiButton = (UIButton *)[footer viewWithTag:203];
        [youhuiButton addTarget:self action:@selector(youhuiButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        UITextField *textfield = (UITextField *)[footer viewWithTag:101];
        textfield.placeholder = NSLocalizedString(@"(Optional),fill in requirements with sellers", nil);
        textfield.delegate = self;
        
        UILabel *label = (UILabel *)[footer viewWithTag:102];
        label.text = NSLocalizedString(@"Buyers comment", nil);
        
        NSString *headerCommodityId = self.payList[section][0][@"commodityId"];
        NSArray *goodList = self.payList[section];
        
        for (NSDictionary *dic in _priceList) {
            NSString *commodityId = dic[@"commodityId"];
            if ([headerCommodityId isEqualToString:commodityId]) {
                UILabel *numLabel = (UILabel *)[footer viewWithTag:103];
                UILabel *priceLabel = (UILabel *)[footer viewWithTag:104];
                UILabel *expressLabel = (UILabel *)[footer viewWithTag:105];
                
                NSString *expressPrice = dic[@"expressPrice"];
                NSString *totalPrice = dic[@"totalPrice"];
                if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
                    numLabel.text = [NSString stringWithFormat:@"All %lu items quantity:",(unsigned long)goodList.count];
                    priceLabel.text = [NSString stringWithFormat:@"¥%.2f",[totalPrice floatValue]];
                    expressLabel.text = [NSString stringWithFormat:@"(Delivery fee included:%.2f)",[expressPrice floatValue]];
                    
                } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
                    numLabel.text = [NSString stringWithFormat:@"档爸︽岛邦︽池︽霸%lu地罢邦﹀ 搬成扳邦︽伴捶半﹀:",(unsigned long)goodList.count];
                    priceLabel.text = [NSString stringWithFormat:@"¥%.2f",[totalPrice floatValue]];
                    expressLabel.text = [NSString stringWithFormat:@"(彼办︽鳖︽伴吵邦﹀:%.2f)",[expressPrice floatValue]];
                    
                    numLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                    priceLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                    expressLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
                    
                } else {
                    numLabel.text = [NSString stringWithFormat:@"共%lu种商品 合计：",(unsigned long)goodList.count];
                    priceLabel.text = [NSString stringWithFormat:@"¥%.2f",[totalPrice floatValue]];
                    expressLabel.text = [NSString stringWithFormat:@"(含运费:¥%.2f)",[expressPrice floatValue]];
                }
                
                break;
            }
        }
        
        UILabel *nameLabel = (UILabel *)[footer viewWithTag:202];
        UIButton *button = (UIButton *)[footer viewWithTag:203];
        NSString *name = self.payList[section][0][@"couponName"];
        if (![name isEqual:[NSNull null]] && name.length > 0) {
            nameLabel.textColor = RGBColor(51, 51, 51);
            nameLabel.text = name;
            [footer viewWithTag:204].hidden = NO;
            button.enabled = YES;
        } else {
            nameLabel.textColor = RGBColor(102, 102, 102);
            nameLabel.text = @"无可使用优惠券";
            [footer viewWithTag:204].hidden = YES;
            button.enabled = NO;
        }
        
        
        return footer;
    }
    return nil;
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //  解决键盘挡住tableView问题
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= kScreen_Width - 216) {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
        [_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    UIView *footer = textField.superview;
    long section = footer.tag - 800;
    NSMutableDictionary *dic = (NSMutableDictionary *)_orderList[section];
    [dic setValue:textField.text forKey:@"remark"];
    
    // 恢复键盘多出的高度
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - IBActions

- (IBAction)backButtonPressed:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)sendFirstButton:(UIButton *)sender {
    if (self.isConveniency) {// 背兜超人
        _expressType = @"BD";
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        });
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:NSLocalizedString(@"Please select the area you are in", nil)
                                      delegate:self
                                      cancelButtonTitle:nil
                                      destructiveButtonTitle:nil
                                      otherButtonTitles:NSLocalizedString(@"old city", nil)
                                      ,NSLocalizedString(@"new city", nil)
                                      ,NSLocalizedString(@"southern suburbs", nil),nil];
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        [actionSheet showInView:self.view];
        
    } else {
        _expressType = @"REMOTE";
        [self calculateSingleOrder];
    }
    sender.selected = YES;
    
    UIView *view = sender.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    UIButton *secondButton = (UIButton *)[cell viewWithTag:102];
    if (secondButton) {
        secondButton.selected = NO;
    }
}


- (IBAction)sendSecondButton:(UIButton *)sender {
    _expressType = @"ONESELF";
    
    sender.selected = YES;
    UIView *view = sender.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    UIButton *secondButton = (UIButton *)[cell viewWithTag:101];
    secondButton.selected = NO;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    });
    [self calculateSingleOrder];
}

- (IBAction)payFirstButton:(UIButton *)sender {
    _payType = @"ALIPAY";
    
    sender.selected = YES;
    
    UIView *view = sender.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    UIButton *secondButton = (UIButton *)[cell viewWithTag:102];
    secondButton.selected = NO;
}


- (IBAction)paySecondButton:(UIButton *)sender {
    _payType = @"WECHAT";
    
    sender.selected = YES;
    
    UIView *view = sender.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    UIButton *secondButton = (UIButton *)[cell viewWithTag:101];
    secondButton.selected = NO;
}

- (IBAction)payButtonPressed:(UIButton *)sender {
    [self commitOrder];
}

- (IBAction)closePopView:(UIButton *)sender {
    self.popView.hidden = YES;
}

- (IBAction)youhuiSelectedButtonPressed:(UIButton *)sender {
    UIView *view = sender.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    
    NSIndexPath *indexPath = [_youhuiTableView indexPathForCell:cell];
    NSDictionary *youhuiDic = _youhuiList[indexPath.row];
    NSString *coupon_ID = youhuiDic[@"id"];
    NSString *coupon_Name = youhuiDic[@"name"];
    
    NSMutableDictionary *goodDic = _payList[_selectedSection][0];
    [goodDic setValue:coupon_ID forKeyPath:@"couponId"];
    [goodDic setValue:coupon_Name forKeyPath:@"couponName"];
    
    [self calculateSingleOrder];
    self.popView.hidden = YES;
}



#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {// 老城区
        _bdAddress = @"OLD_CITY";
    } else if (buttonIndex == 1) {// 新城区
        _bdAddress = @"NEW_CITY";
    } else if (buttonIndex == 2) {// 南郊
        _bdAddress = @"SOUTH";
    }
    [self calculateSingleOrder];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
